import {
  asyncRoutes,
  constantRoutes
} from '@/router'
import {
  deepClone,
} from '@/utils'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return true
    // return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    // let rou = constantRoutes
    // rou.splice(-2, 0, ...routes)
    // state.routes = rou
    state.routes = constantRoutes.concat(routes)
  },
  CLEAN_ROUTE: (state) => {
    state.routesMap = null
    state.firstRoute = null
    state.routes = []
    state.addRoutes = []
  }
}

const actions = {
  cleanRoute({
    commit
  }) {
    console.log('123123')
    commit('CLEAN_ROUTE')
  },
  generateRoutes({
    commit
  }, auth) {
    return new Promise(resolve => {
      // console.log('==========')
      // console.log(auth)
      // console.log('xxxxxxxx')
      let {
        permissions,
        menus
      } = auth
      let menuIdMap = {}
      // permissions 这是取回来的 用户有的路由 与menus相同的是 MenuId 和 Id 的配置
      // menus 这是取回来的 系统中配置的路由 与asyncRoutes相同的是 Remark 与 name  
      // asyncRoutes 这是本地前端中配置的路由 
      // console.log('用户', permissions)
      // console.log('系统', menus)
      // console.log('前端', asyncRoutes)
      permissions.forEach(item => {
        menuIdMap[item.MenuId] = true
      })
      let pathMap = {}

      let queue = menus
      while (queue.length > 0) {
        let menu = queue.shift()
        for (let item in menuIdMap) {
          if (menu.Id == item) {
            //如果在系统列表找到用户有的页面
            pathMap[menu.Remark] = menu
            if (menu.ChildList && menu.ChildList.length > 0) {
              menu.ChildList.forEach(child => {
                queue.push(child)
              })
            }
          }
        }
      }
      // console.log(pathMap)
      let listt = deepClone(asyncRoutes)
      console.log('处理一次',listt)
      function dealAsyRouter(arr) {
        for (let i = 0; i < arr.length; i++) {

          if (pathMap[arr[i].name]) {
            // newRouter.push({...arr[i],children:[]})
            console.log(arr[i])
            let {MenuName} = pathMap[arr[i].name]
            if(arr[i].meta && arr[i].meta.title){
               arr[i].meta.title = MenuName|| '未设置或失败'
            }
           
            arr[i].permiss = true
            arr[i].meta && arr[i].meta.icon && (arr[i].meta.icon = pathMap[arr[i].name].MenuIcon)
            if (arr[i].children && arr[i].children.length > 0) {
              dealAsyRouter(arr[i].children)
            }
          }
        }
      }

      dealAsyRouter(listt)
      console.log('处理2次',listt)

      function filterRouter(arr) {
        for (let i = 0; i < arr.length; i++) {
          if (!arr[i].permiss) {
            arr[i] = null
            // arr[i].splice(i, 1)
          } else {
            if (arr[i].children && arr[i].children.length > 0) {
              filterRouter(arr[i].children)
            }
          }
        }
      }
      filterRouter(listt)
      // console.log('开始尝试删除假值')
      // console.log(listt)

      function comactObject(val) {
        const data = Array.isArray(val) ? val.filter(Boolean) : val;
        return Object.keys(data).reduce((acc, key) => {
            const value = data[key]
            if (value) {
              acc[key] = typeof value === 'object' ? comactObject(value) : value
            }
            return acc
          },
          Array.isArray(data) ? [] : {}
        )

      }
      let newarrs = comactObject(listt)
      // console.log(newarrs)
      let accessedRoutes = newarrs || []
      // asyncRoutes
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
